//
//  DWCustomPlayerViewController.m
//  StudyPay
//
//  Created by TopSageOSX on 14-8-7.
//  Copyright (c) 2014年 com.topsage. All rights reserved.
//

#import "DWCustomPlayerViewController.h"
@interface DWCustomPlayerViewController ()
/**
 *  主要的播放器
 */
@property (nonatomic,strong)DWMoviePlayerController *player;
//播放器覆盖视图
@property (strong, nonatomic)UIView *overlayView;
//播放器背景视图
@property (strong, nonatomic)UIView *videoBackgroundView;
/**
 *  顶部视图
 *  @param backBtn 返回钮
 *  @param titleLabel 标题栏
 *  @param qualityBtn 清晰度
 */
@property (strong, nonatomic)UIView *topView;
@property (strong, nonatomic)UIButton *backBtn;
@property (strong, nonatomic)UILabel *titleLabel;
@property (strong, nonatomic)UIButton *qualityBtn;
/**
 *  底部视图
 *  @param progressSlider 进度条
 *  @param playBtn 播放/暂停按钮
 *  @param currentTime 当前时间
 *  @param duration 总时间
 *  @param sizeBtn 缩放
 */
@property (strong, nonatomic)UIView *bottomView;
@property (strong, nonatomic)UIButton *playBtn;
@property (strong, nonatomic)UISlider *progressSlider;
@property (strong, nonatomic)UILabel *currentTime;
@property (strong, nonatomic)UIButton *sizeBtn;
/**
 *  左部视图
 *  @param voiceSlider 音量(竖着的,需要偏转)
 *  @param voiceLabel 音量数字
 */
@property (strong, nonatomic)UIView *leftView;
@property (strong, nonatomic)UISlider *voiceSlider;
@property (strong, nonatomic)UILabel *voiceLabel;
/**
 *  右部视图
 *  @param subtitleBtn 字幕按钮(显示/不显示)
 */
@property (strong, nonatomic)UIView *rightView;
@property (strong, nonatomic)UIButton *subtitleBtn;
//视频状态标签
@property (strong, nonatomic)UILabel *videoStatusLabel;
@property (strong, nonatomic)NSDictionary *playUrls;
@property (strong, nonatomic)NSDictionary *currentPlayUrl;
//清晰度数组
@property (strong, nonatomic)NSArray *qualityDescription;
//当前清晰度
@property (strong, nonatomic)NSString *currentQuality;
@end

@implementation DWCustomPlayerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _qualityDescription = @[@"普通", @"清晰", @"高清"];
        //根据是否免费来
        if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"KEY_DWACCOUNT"] isEqualToString:@"LY_FREE"]) {
            _player = [[DWMoviePlayerController alloc]initWithUserId:DWACCOUNT_USERID_FREE key:DWACCOUNT_APIKEY_FREE];
        }else{
            _player = [[DWMoviePlayerController alloc]initWithUserId:DWACCOUNT_USERID key:DWACCOUNT_APIKEY];
        }
        ;
        
        
        _currentQuality = [_qualityDescription objectAtIndex:0];
    }
    return self;
}
/**
 *  调整屏幕方向
 */
- (void)doForceScreenRotate
{
    CGRect frame = self.view.frame;
    [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO];
    [self.view setTransform:CGAffineTransformMakeRotation(M_PI/2)];
    
    if (IOS7_OR_LATER) {
        self.view.frame = CGRectMake(0, 0, frame.size.height, frame.size.width);
        
    } else {
        self.view.frame = CGRectMake(-20, 0, frame.size.height + 20, frame.size.width - 20);
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置Drm
    self.player.drmServerPort = DWAPPDELEGATE.drmServer.listenPort;
    //默认横向
    [self doForceScreenRotate];
    //隐藏导航栏
    self.navigationController.navigationBarHidden = YES;
    //隐藏状态栏
    [UIApplication sharedApplication].statusBarHidden = YES;
    self.view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.8];
    //--加载所需视图
    // 加载播放器 必须第一个加载
    [self loadPlayer];
    // 加载播放器覆盖视图，它作为所有空间的父视图。
    self.overlayView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.overlayView.backgroundColor = [UIColor clearColor];
    //创建状态标签
    self.videoStatusLabel = [[UILabel alloc]initWithFrame:CGRectMake((SCREEN_HEIGHT-100)/2, (SCREEN_WIDTH-30)/2, 100, 30)];
    self.videoStatusLabel.font = [UIFont boldSystemFontOfSize:20];
    self.videoStatusLabel.textColor = [UIColor whiteColor];
    self.videoStatusLabel.text = @"加载中...";
    [self.view addSubview:self.videoStatusLabel];
    
    CGRect frame = CGRectZero;
    if (IOS7_OR_LATER) {
        frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        
    } else {
        frame = CGRectMake(-20, 0, self.view.frame.size.width, self.view.frame.size.height);
    }
    self.overlayView.frame = frame;
    
    [self.view addSubview:self.overlayView];
    
    if (self.videoId) {
        // 获取videoId的播放url
        [self loadPlayUrls];
        
    } else if (self.videoLocalPath) {
        // 播放本地视频
        [self playLocalVideo];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"没有可以播放的视频"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil, nil];
        [alert show];
    }
    //
    [self creatTopView];

}
//隐藏电池栏
-(BOOL)prefersStatusBarHidden{
    return YES;
}
/**
 *  创建顶部视图
 */
-(void)creatTopView{
    self.topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, 60)];
    //半透明背景
    UIView *bgView = [[UIView alloc]initWithFrame:self.topView.bounds];
    bgView.backgroundColor = [UIColor blackColor];
    bgView.alpha = 0.4;
    [self.topView addSubview:bgView];
    [self.view addSubview:self.topView];
    //返回钮
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backBtn.frame = CGRectMake(5, 10, 60, 30);
    [self.backBtn setTitle:@"<返回" forState:UIControlStateNormal];
    [self.backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.backBtn];
    //标题栏
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 10, SCREEN_HEIGHT-100-100, 40)];
    self.titleLabel.text = self.videoName;
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.topView addSubview:self.titleLabel];
}
/**
 *  加载播放器
 */
- (void)loadPlayer
{
    CGRect frame = CGRectZero;
    
    frame = self.view.frame;
    if (IOS7_OR_LATER) {
        frame.origin.x = 0;
        frame.origin.y = 0;
        
    } else {
        frame.size.height += 20; //加上状态栏的高度
    }
    //背景
    self.videoBackgroundView = [[UIView alloc] initWithFrame:frame];
    self.videoBackgroundView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.videoBackgroundView];
    
    self.player.scalingMode = MPMovieScalingModeAspectFit;
    self.player.controlStyle = MPMovieControlStyleNone;
    self.player.view.backgroundColor = [UIColor clearColor];
    self.player.view.frame = self.videoBackgroundView.bounds;
    
    [self.videoBackgroundView addSubview:self.player.view];
}

/**
 *  播放在线视频
 */
- (void)loadPlayUrls
{
    logdebug(@"在线");
    self.player.videoId = self.videoId;
    self.player.timeoutSeconds = 10;
    
    __block DWCustomPlayerViewController *blockSelf = self;
    self.player.failBlock = ^(NSError *error) {
        NSLog(@"error: %@", [error localizedDescription]);
        blockSelf.videoStatusLabel.hidden = NO;
        blockSelf.videoStatusLabel.text = @"加载失败";
    };
    
    self.player.getPlayUrlsBlock = ^(NSDictionary *playUrls) {
        // [必须]判断 status 的状态，不为"0"说明该视频不可播放，可能正处于转码、审核等状态。
        NSNumber *status = [playUrls objectForKey:@"status"];
        //显示不可播放的原因
        if (status == nil || [status integerValue] != 0) {
            NSString *message = [NSString stringWithFormat:@"%@ %@:%@",
                                 blockSelf.videoId,
                                 [playUrls objectForKey:@"status"],
                                 [playUrls objectForKey:@"statusinfo"]];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:message
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        blockSelf.playUrls = playUrls;
        [blockSelf resetViewContent];
    };
    
    [self.player startRequestPlayInfo];
}

/**
 *  根据播放url更新涉及的视图
 */
- (void)resetViewContent
{
    // 获取默认清晰度播放url
    NSNumber *defaultquality = [self.playUrls objectForKey:@"defaultquality"];
    
    for (NSDictionary *playurl in [self.playUrls objectForKey:@"qualities"]) {
        if (defaultquality == [playurl objectForKey:@"quality"]) {
            self.currentPlayUrl = playurl;
            break;
        }
    }
    
    if (!self.currentPlayUrl) {
        self.currentPlayUrl = [[self.playUrls objectForKey:@"qualities"] objectAtIndex:0];
    }
    
    [self.player prepareToPlay];
    [self.player play];
    self.videoStatusLabel.hidden = YES;
}

# pragma mark - 播放本地文件
- (void)playLocalVideo
{
    self.playUrls = [NSDictionary dictionaryWithObject:self.videoLocalPath forKey:@"playurl"];
    logdebug(@"本地%@",self.playUrls);
    self.videoStatusLabel.hidden = YES;
    self.player.contentURL = [[NSURL alloc] initFileURLWithPath:self.videoLocalPath];
    
    [self.player prepareToPlay];
    [self.player play];
}

/**
 *  视图将要消失的时候调用
 */
- (void)viewWillDisappear:(BOOL)animated
{
    [self.player cancelRequestPlayInfo];
    self.player.currentPlaybackTime = self.player.duration;
    self.player.contentURL = nil;
    [self.player stop];
    
    
    /**
     *  NOTE: 顺序必须为：
     *      调整屏幕方向 -> 显示 状态栏 -> 显示 navigationController
     *  否则返回播放列表页面时，导航栏的尺寸会发生变化。
     */
    
    // 调整屏幕方向
    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
    self.view.transform = CGAffineTransformMakeRotation(-M_PI/2);
    
    // 显示 状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    // 显示 navigationController
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

/**
 *  旋转自动适应
 */
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    switch (toInterfaceOrientation) {
        case 3:
            [self.view setTransform:CGAffineTransformMakeRotation(0)];
            break;
        case 4:
            [self.view setTransform:CGAffineTransformMakeRotation(0)];
            break;
        case 1:
            [self.view setTransform:CGAffineTransformMakeRotation(M_PI/2)];
            break;
            
        default:
            break;
    }
    
}

-(void)backToLastView{
    //全部清理掉
    [self.navigationController popViewControllerAnimated:YES];
}
//----------------------------
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
